package com.youi.web;

import java.text.ParseException;
import java.util.*;
import java.util.concurrent.ScheduledThreadPoolExecutor;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.youi.exception.BusinessException;
import com.youi.manage.HttpRequestManage;
import com.youi.manage.HttpSessionManage;
import com.youi.common.DelStatus;
import com.youi.common.SessionKey;
import com.youi.service.GoodsService;
import com.youi.service.GoodsandgoodscarService;
import com.youi.service.GoodscarService;
import com.youi.service.GoodssizeService;
import com.youi.entity.Goods;
import com.youi.entity.Goodsandgoodscar;
import com.youi.entity.Goodscar;
import com.youi.entity.Goodssize;
import com.youi.entity.User;
import com.youi.common.Common;
import com.youi.util.CommonInfoUtil;
import com.youi.util.JsonUtil;

/**
* Goodscar控制层
* @author Administrator
*/
@Controller
public class GoodscarController  extends HttpRequestManage implements ApplicationContextAware{

		@Autowired
		private GoodscarService goodscarService;
		@Autowired
		private GoodsandgoodscarService goodsandgoodscarService;
		@Autowired
		private GoodssizeService goodssizeService;
		@Autowired
		private GoodsService goodsService;

		/**同步静态对象 零长度的byte数组对象创建起来将比任何对象都经济――查看编译后的字节码：生成零长度的byte[]对象只需3条操作码，而Object lock = new Object()则需要7行操作码*/
		private static byte[] lock =null;
		/**
		 * M-9
		 * 查询购物车详情
		*/
		@ResponseBody
		@RequestMapping("userGetInfo/getGoodscarByUserId")
		public String getGoodscarBymerchantId(ModelMap modelMap,HttpServletRequest request) throws BusinessException{
			User user=(User) HttpSessionManage.getAttribute(request, SessionKey.USER);
			Map<String, Object> prams=new HashMap<String, Object>();
			prams.put(Common.DELSTATUS, DelStatus.NODEL);
			prams.put(Common.USERID, user.getId());
			Goodscar goodscar=goodscarService.getByParam(prams);
			if (goodscar==null) {
				return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
			}
			goodscarService.getGoodscarMsg(goodscar);
			return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成",goodscar);//jsonObject	json对象
		}
		
		/**
		 * M-10
		 * 添加商品进购物车
		 * @param modelMap
		 * @param request
		 * @return
		 * @throws BusinessException
		 * @throws ParseException
		 */
		@ResponseBody
		@RequestMapping("userGetInfo/addGoodsInGoodscar")
		public String addGoodsInGoodscar(ModelMap modelMap,HttpServletRequest request)throws BusinessException,ParseException{
			synchronized (lock) {
				User user=(User) HttpSessionManage.getAttribute(request, SessionKey.USER);
				Long goodsId=getLong("goodsId", request);
				Integer count=getInteger("count", request);
				Long goodsSizeId=getLong("goodsSizeId", request);
				Map<String, Object> prams=new HashMap<String, Object>();
				prams.put(Common.DELSTATUS, DelStatus.NODEL);
				prams.put(Common.USERID, user.getId());
				Goodscar goodscar=goodscarService.getByParam(prams);
				if (goodscar==null) {
					goodscar=new Goodscar(user.getId(), 0.00);
					goodscarService.saveOrUpdate(goodscar);
				}
				Goodssize goodssize=goodssizeService.get(goodsSizeId);
				if (goodssize==null) {
					return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "商品规格不存在");
				}
				if (count>goodssize.getStockNum()) {
					return JsonUtil.toJson(CommonInfoUtil.ISLOCK, "商品库存不足");
				}
				prams=new HashMap<String, Object>();
				prams.put(Common.DELSTATUS, DelStatus.NODEL);
				prams.put(Common.ID, goodssize.getGoodsId());
				Goods goods=goodsService.getByParam(prams);
				if (goods==null||goods.getStatus()!=1) {
					return JsonUtil.toJson(CommonInfoUtil.NOPERMISSIONS, "商品不存在或非出售状态无法添加到购物车");
				}
				prams=new HashMap<String, Object>();
				prams.put(Common.DELSTATUS, DelStatus.NODEL);
				prams.put("goodsId", goodsId);
				prams.put("goodscarId", goodscar.getId());
				prams.put("goodssizeId", goodsSizeId);
				Goodsandgoodscar goodsandgoodscar=goodsandgoodscarService.getByParam(prams);
				if (goodsandgoodscar!=null) {
					if (goodsandgoodscar.getCount()>goodssize.getRealStockNum()) {
						return JsonUtil.toJson(CommonInfoUtil.NOPERMISSIONS, "购物车该商品数量大于当前库存");
					}
					goodsandgoodscar.setCount(goodsandgoodscar.getCount()+count);
					Double amount=goodssize.getPrice()*count;
					goodsandgoodscar.setAmount(goodsandgoodscar.getAmount()+amount);
				}else {
					goodsandgoodscar=new Goodsandgoodscar(goodscar.getId(), goodsId,goodsSizeId,goodssize.getSpecification(), count,count*goodssize.getPrice());
				}
				goodscar.setAmount(goodscar.getAmount()+goodsandgoodscar.getAmount());
				goodscarService.saveOrUpdate(goodscar);
				goodsandgoodscarService.saveOrUpdate(goodsandgoodscar);
				return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成");
			}
		}

//		private static class TestGoodssize{
//			long goodsId;
//			long goodssizeId;
//			String specification;
//			double price;
//			TestGoodssize(long goodsId,long goodssizeId,String specification,double price){
//				this.goodsId = goodsId;
//				this.goodssizeId = goodssizeId;
//				this.specification = specification;
//				this.price = price;
//			}
//		}
//
//		static private ArrayList<TestGoodssize> testGoodsAndSizeData = new ArrayList<>();{
//		testGoodsAndSizeData.add(new TestGoodssize(861,1399,"2袋装/份（100只/袋）",19.80));
//		testGoodsAndSizeData.add(new TestGoodssize(869,1407,"100ml*3",39.90));
//		testGoodsAndSizeData.add(new TestGoodssize(871,1409,"500ml/瓶",49.90));
//		testGoodsAndSizeData.add(new TestGoodssize(874,1413,"1KG/瓶*2",35.00));
//		testGoodsAndSizeData.add(new TestGoodssize(878,1417,"100球*1瓶",29.00));
//		}
//
//	@ResponseBody
//	@RequestMapping("userGetInfo/testAddGoodsInGoodscar")
//	public String testAddGoodsInGoodscar(ModelMap modelMap,HttpServletRequest request)throws BusinessException,ParseException {
//		User user=(User) HttpSessionManage.getAttribute(request, SessionKey.USER);
//		Map<String, Object> prams=new HashMap<String, Object>();
//		prams.put(Common.DELSTATUS, DelStatus.NODEL);
//		prams.put(Common.USERID, user.getId());
//		Goodscar goodscar=goodscarService.getByParam(prams);
//
//		Random rnd = new Random();
//		int selectedCount = rnd.nextInt(4)+1;
//		System.out.println(selectedCount);
//		Collections.shuffle(testGoodsAndSizeData);
//		double amountAll = 0.0;
//		String results = "";
//		for(int i=0;i<selectedCount;i++){
//			TestGoodssize data = testGoodsAndSizeData.get(i);
//			int count = rnd.nextInt(4)+1;
//			double amount = count*data.price;
//			amountAll += amount;
//			Goodsandgoodscar goodsandgoodscar=new Goodsandgoodscar(
//					goodscar.getId(), data.goodsId,data.goodssizeId,
//					data.specification, count,amount);
//			goodsandgoodscarService.saveOrUpdate(goodsandgoodscar);
//			if (results.length()>0){
//				results += ",";
//			}
//			results += goodsandgoodscar.getId();
//		}
//		goodscar.setAmount(goodscar.getAmount()+amountAll);
//		return JsonUtil.toJson(CommonInfoUtil.SUCCESS, results);
//	}


		/**
		 *根据id查询Goodscar
		*/
		@ResponseBody
		@RequestMapping("getGoodscarById")
		public String getGoodscarById(ModelMap modelMap,HttpServletRequest request) throws BusinessException{
			Long id=getLong("id",request);
			Goodscar goodscar=goodscarService.get(id);
			if (goodscar==null) {
				return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
			}
			return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成",goodscar);//jsonObject	json对象
		}

		/**
		 * 查询所有Goodscar
		 * @param modelMap
		 * @param session
		 * @return
		 */
		@ResponseBody
		@RequestMapping("getAllGoodscar")
		public String getAllGoodscar(ModelMap modelMap,HttpServletRequest request) throws BusinessException{
			List<Goodscar> goodscarList= goodscarService.getByParams(null);
			if (goodscarList==null||goodscarList.size()==0) {
				return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
			}
			return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成",goodscarList);//jsonObjectList	json对象集合
		}

		/**定时器线程池*/
		private static ScheduledThreadPoolExecutor executor;
		@Override
		public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
			// TODO Auto-generated method stub
			if (lock==null) {
				lock = new byte[0];
				executor=new ScheduledThreadPoolExecutor(1);				
			}
		}
}
